/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.auth.shiro.jwt.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.zfes.snowy.auth.shiro.handlers.IAuthecFailureHandler;
import org.zfes.snowy.auth.shiro.jwt.token.JWTTokenParser;
import org.zfes.snowy.auth.shiro.jwt.token.JwtAuthToken;
import org.zfes.snowy.core.consts.FrameConst;

public class SnowyJwtAuthTokenFilter extends AccessControlFilter{
	
	private IAuthecFailureHandler jwtAuthenticationFailureHandler;
	
	@Override
	protected boolean isAccessAllowed(ServletRequest arg0, ServletResponse arg1, Object arg2) throws Exception {
		return false;
	}

	//返回 view 自定义处理
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		
	    String jwtTokenStr=JWTTokenParser.getTokenFromRequest(httpRequest,FrameConst.TOKENS.JWT_AUTH_TOKEN);
	    
	    try {  
		    getSubject(request, response).login(new JwtAuthToken(jwtTokenStr));  
	    } catch (AuthenticationException e) {  
		      jwtAuthenticationFailureHandler.onAuthenticationFailure(httpRequest, httpResponse, e);
		      return false;
	    }  
	    return true; 
	}

	
	
	public IAuthecFailureHandler getJwtAuthenticationFailureHandler() {
		return jwtAuthenticationFailureHandler;
	}

	public void setJwtAuthenticationFailureHandler(IAuthecFailureHandler jwtAuthenticationFailureHandler) {
		this.jwtAuthenticationFailureHandler = jwtAuthenticationFailureHandler;
	}
    
    
}
